const express = require('express');
const jwt = require('jsonwebtoken');
const cors = require('cors');

const app = express();
const PORT = 3001;

// 允许跨域
app.use(cors());

// 解析JSON请求体
// app.use(express.json());
// 解析URL编码的请求体（用于form-data）
app.use(express.urlencoded({ extended: true }));
// Mock用户数据
const users = {
  'user1': { password: 'password1' },
  'user2': { password: 'password2' },
};

// 登录接口
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users[username];

  if (user && user.password === password) {
    const token = jwt.sign({ username }, 'your-secret-key', { expiresIn: '1h' });
    res.json({ data:token,msg:'恭喜你，登录成功',code:0 });
  } else {
    res.status(401).send('Username or password is incorrect');
  }
});

// 验证token的中间件
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (token == null) return res.sendStatus(401);

  jwt.verify(token, 'your-secret-key', (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

// 获取用户信息接口
app.get('/userinfo', authenticateToken, (req, res) => {
  res.json({ message: `Hello ${req.user.username}!` });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});